"""
cv2_cheatsheet.py
-----------------
OpenCV (cv2) 常用函数速查示例

用法:
    python cv2_cheatsheet.py <示例编号>

示例编号:
    1 - 读写与显示图片
    2 - 调整大小 / 裁剪 / 翻转
    3 - 颜色空间转换
    4 - 滤波 / 去噪 / 锐化
    5 - 边缘检测 / 轮廓
    6 - 二值化
    7 - 形态学操作
    8 - 绘图（矩形、圆、文字）
    9 - 视频读取（摄像头）
"""

import cv2
import numpy as np
import sys
import os


def example1():
    """读写与显示图片"""
    img = cv2.imread("test.jpg")
    if img is None:
        print("⚠️ 没找到 test.jpg，请放一张图片到脚本目录下")
        return
    cv2.imshow("Original", img)
    cv2.imwrite("out_example1.jpg", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def example2():
    """调整大小 / 裁剪 / 翻转"""
    img = cv2.imread("test.jpg")
    if img is None:
        print("⚠️ 没找到 test.jpg")
        return
    resized = cv2.resize(img, (400, 300))
    cv2.waitKey(0)
    crop = img[50:200, 100:300]
    cv2.waitKey(0)
    flip = cv2.flip(img,-1)

    cv2.waitKey(0)
    cv2.imshow("Resized", resized)
    cv2.imshow("Crop", crop)
    cv2.imshow("Flip", flip)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def example3():
    """颜色空间转换"""
    img = cv2.imread("test.jpg")
    if img is None:
        print("⚠️ 没找到 test.jpg")
        return
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    cv2.imshow("Gray", gray)
    cv2.imshow("HSV", hsv)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def example4():
    """滤波 / 去噪 / 锐化"""
    img = cv2.imread("test.jpg")
    if img is None:
        print("⚠️ 没找到 test.jpg")
        return
    blur = cv2.GaussianBlur(img, (5, 5), 0)
    median = cv2.medianBlur(img, 5)
    kernel = np.array([[0, -1, 0],
                       [-1, 5, -1],
                       [0, -1, 0]])
    sharpen = cv2.filter2D(img, -1, kernel)

    cv2.imshow("Blur", blur)
    cv2.imshow("Median", median)
    cv2.imshow("Sharpen", sharpen)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def example5():
    """边缘检测 / 轮廓"""
    img = cv2.imread("test.jpg")
    if img is None:
        print("⚠️ 没找到 test.jpg")
        return
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 50, 150)
    ret, th = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
    contours, _ = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(img, contours, -1, (0, 255, 0), 2)

    cv2.imshow("Edges", edges)
    cv2.imshow("Contours", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def example6():
    """二值化"""
    img = cv2.imread("test.jpg", cv2.IMREAD_GRAYSCALE)
    if img is None:
        print("⚠️ 没找到 test.jpg")
        return
    _, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    th2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                cv2.THRESH_BINARY, 11, 2)

    cv2.imshow("Global Threshold", th1)
    cv2.imshow("Adaptive Threshold", th2)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def example7():
    """形态学操作"""
    img = cv2.imread("test.jpg", cv2.IMREAD_GRAYSCALE)
    if img is None:
        print("⚠️ 没找到 test.jpg")
        return
    _, th = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    eroded = cv2.erode(th, kernel)
    dilated = cv2.dilate(th, kernel)
    opened = cv2.morphologyEx(th, cv2.MORPH_OPEN, kernel)
    closed = cv2.morphologyEx(th, cv2.MORPH_CLOSE, kernel)

    cv2.imshow("Eroded", eroded)
    cv2.imshow("Dilated", dilated)
    cv2.imshow("Opened", opened)
    cv2.imshow("Closed", closed)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def example8():
    """绘图"""
    img = np.zeros((400, 400, 3), dtype=np.uint8) + 255
    cv2.rectangle(img, (50, 50), (200, 200), (0, 255, 0), 2)
    cv2.circle(img, (300, 300), 50, (255, 0, 0), -1)
    cv2.putText(img, "Hello OpenCV", (50, 350),
                cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)

    cv2.imshow("Drawings", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def example9():
    """视频读取（摄像头）"""
    cap = cv2.VideoCapture(0)  # 0 默认摄像头
    if not cap.isOpened():
        print("⚠️ 无法打开摄像头")
        return
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        cv2.imshow("Camera", frame)
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    cap.release()
    cv2.destroyAllWindows()

def example10():
    # 加载人脸检测的 Haar Cascade 模型
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

    # 打开摄像头
    cap = cv2.VideoCapture(0)

    while True:
        ret, frame = cap.read()
        if not ret:
            break

        # 转灰度图（人脸检测需要灰度图）
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # 检测人脸，返回人脸区域的坐标
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)

        # 在检测到的人脸区域画矩形
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

        # 显示画面
        cv2.imshow("Face Detection", frame)

        # 按 q 退出
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()


if __name__ == "__main__":
    examples = {
        "1": example1,
        "2": example2,
        "3": example3,
        "4": example4,
        "5": example5,
        "6": example6,
        "7": example7,
        "8": example8,
        "9": example9,
        "10": example10,
    }

    if len(sys.argv) < 2 or sys.argv[1] not in examples:
        print(__doc__)
        sys.exit(1)

    examples[sys.argv[1]]()
